<!--
 * @Author: hucc
 * @Date: 2021-09-27 11:28:05
 * @LastEditors: hucc
 * @LastEditTime: 2021-10-06 16:54:04
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖</title>
</head>

<body>
    <input type="text">
    <script>
        const input = document.querySelector("input")
            // let timer;
            // input.oninput = function() {
            //     if  (timer ) {
            //          clearTimeout(timer);
            //     }
            //     timer   = setTimeout( ()  => {
            //         console.log(this.value);
            //     },  1000)

        // }
        //实现封装代码与实际业务相分离 
        //2.实际业务需求
        input.oninput = timeOut(function() {
            console.log(this.value);
        }, 500);
        //1.封装防抖代码
        function timeOut(fn, delay) {
            let timer;
            return function() {
                if (timer) {
                    clearTimeout(timer);
                }
                timer = setTimeout(() => {
                    //箭头函数的this指向声明时外部作用域的this 这里箭头函数指向input
                    //console.log(this);
                    //改变fn this指向，原本指向window 改变之后让它指向input
                    fn.call(this);
                }, delay)
            }
        }
    </script>
</body>

</html>